import { reactive } from "vue";
import type { FormRules } from "element-plus";
import { isPhone, isEmail } from "@pureadmin/utils";

/** 密码校验规则 */
function isPassword(value: string): boolean {
  return typeof value === "string" && value.length >= 6 && value.length <= 15;
}

/** 自定义表单规则校验 */
export const formRules = reactive(<FormRules>{
  username: [{ required: true, message: "用户名为必填项", trigger: "blur" }],
  password: [
    {
      trigger: "blur",
      required: true,
      validator: (rule, value, callback) => {
        if (value === "") {
          callback(new Error("请输入用户密码"));
        } else if (!isPassword(value)) {
          callback(new Error("密码长度需为6到15位"));
        } else {
          callback();
        }
      }
    }
  ],
  phone: [
    {
      trigger: "blur",
      required: true,
      validator: (rule, value, callback) => {
        if (value === "") {
          callback(new Error("请输入手机号码"));
        } else if (!isPhone(value)) {
          callback(new Error("请输入正确的手机号码格式"));
        } else {
          callback();
        }
      }
      // trigger: "click" // 如果想在点击确定按钮时触发这个校验，trigger 设置成 click 即可
    }
  ],
  useremail: [
    {
      validator: (rule, value, callback) => {
        if (value === "") {
          callback();
        } else if (!isEmail(value)) {
          callback(new Error("请输入正确的邮箱格式"));
        } else {
          callback();
        }
      },
      trigger: "blur",
      required: true
    }
  ]
});
